package com.gmu.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gmu.domain.ResResult;
import com.gmu.domain.vo.PageVo;
import com.gmu.domain.vo.TblOrderVo;
import com.gmu.pojo.BeSampleUnitsActivities;
import com.gmu.pojo.TblActivities;
import com.gmu.pojo.TblOrder;
import com.gmu.service.BeSampleUnitsActivitiesService;
import com.gmu.service.TblOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * <p>
 * 核酸预约 前端控制器
 * </p>
 *
 * @author verb-calming
 * @since 2022-07-27
 */
@Api(value = "预约", tags= "预约管理API")
@RestController
@RequestMapping("/gmu/tbl-order")
public class TblOrderController {

    @Autowired
    private TblOrderService tblOrderService;

    @Autowired
    private BeSampleUnitsActivitiesService beSampleUnitsActivitiesService;

    @ApiOperation(value = "提交核酸预约")
    @PostMapping("/submitReservation")
    @Transactional(rollbackFor = Exception.class)
    public ResResult<?> submitReservation(@RequestBody TblOrder tblOrder) {
        if (!tblOrderService.checkIsReservation(tblOrder.getUserId(),tblOrder.getActivitiesId())) return new ResResult<>(200,"您已经预约或完成了该核酸检测活动");
        return submit(tblOrder);
    }

    @ApiOperation(value = "查询预约列表")
    @GetMapping("/getOrderList/{userId}/{status}")
    public ResResult<?> getOrderList(@PathVariable Integer userId,@PathVariable Integer status) {
        return tblOrderService.getOrderList(userId,status);
    }

    @ApiOperation(value = "查询某用户的预约信息")
    @GetMapping("/getOrderOne/{userId}/{idNumber}/{status}")
    public ResResult<?> getOrderOne(@PathVariable Integer userId,@PathVariable String idNumber,@PathVariable Integer status){
        return tblOrderService.getOrderOneList(userId,idNumber,status);
    }

    @ApiOperation(value = "修改预约")
    @PutMapping("/updateReservation")
    @Transactional(rollbackFor = Exception.class)
    public ResResult<?> updateReservation(@RequestBody TblOrder tblOrder) {
        return modify(tblOrder);
    }

    private ResResult<?> modify(TblOrder tblOrder) {
        Integer orderPeoples = 0;
        if (Objects.equals(tblOrder.getBeSampleId(), tblOrder.getOldBeSampleId())) {
            return new ResResult<>(200,"");
        } else {
            BeSampleUnitsActivities old = beSampleUnitsActivitiesService.getById(tblOrder.getOldBeSampleId());
            System.out.println(old.getOrderedPeoples());
            orderPeoples = old.getOrderedPeoples() - 1;
            System.out.println(orderPeoples);
            beSampleUnitsActivitiesService.updatePeoples(tblOrder.getOldBeSampleId(),orderPeoples);
            BeSampleUnitsActivities beSampleUnitsActivities = beSampleUnitsActivitiesService.getById(tblOrder.getBeSampleId());
            if (Objects.equals(beSampleUnitsActivities.getPeoples(), beSampleUnitsActivities.getOrderedPeoples())) {
                tblOrder.setStatus(0);
                tblOrderService.save(tblOrder);
                return new ResResult<>(200,"当前时间段，预约人数已满，预约失败");
            } else {
                System.out.println(beSampleUnitsActivities.getOrderedPeoples());
                orderPeoples = beSampleUnitsActivities.getOrderedPeoples()==null ? 1:beSampleUnitsActivities.getOrderedPeoples()+1;
                beSampleUnitsActivitiesService.updatePeoples(tblOrder.getBeSampleId(),orderPeoples);
                tblOrderService.update(tblOrder,
                        new UpdateWrapper<TblOrder>().eq("id",tblOrder.getId()).set(true,"status",1));
                return new ResResult<>(200, "修改成功");
            }
        }
    }

    @ApiOperation(value = "删除预约")
    @DeleteMapping("/deleteReservation/{id}")
    @Transactional(rollbackFor = Exception.class)
    public ResResult<?> deleteReservation(@PathVariable Integer id) {
        return tblOrderService.deleteReservation(id);
    }

    private ResResult<?> submit(TblOrder tblOrder) {
        BeSampleUnitsActivities beSampleUnitsActivities = beSampleUnitsActivitiesService.getById(tblOrder.getBeSampleId());
        if (Objects.equals(beSampleUnitsActivities.getPeoples(), beSampleUnitsActivities.getOrderedPeoples())) {
            tblOrder.setStatus(0);
            tblOrderService.save(tblOrder);
            return new ResResult<>(200,"当前时间段，预约人数已满，预约失败");
        } else {
            beSampleUnitsActivitiesService.updatePeoples(tblOrder.getBeSampleId(),beSampleUnitsActivities.getOrderedPeoples()+1);
            tblOrder.setStatus(1);
            tblOrderService.save(tblOrder);
            return new ResResult<>(200, "预约成功");
        }
    }

    @ApiOperation(value = "pc端预约记录")
    @GetMapping("/reservationRecordList")
    public PageVo<?> getReservationRecordList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, TblOrderVo tblOrder, String beginTime, String endTime) {
        return tblOrderService.getReservationRecordList(pageNum,pageSize,tblOrder,beginTime,endTime);
    }

    @ApiOperation(value = "pc端批量删除预约记录")
    @DeleteMapping("/deleteReservationRecord/{ids}")
    public ResResult<?> deleteReservationRecord(@PathVariable Integer[] ids) {
        return tblOrderService.deleteReservationRecord(ids);
    }

    @ApiOperation(value = "导出预约记录数据")
    @GetMapping("/exportRecord")
    public void export(HttpServletResponse response,TblOrderVo tblOrder,String beginTime,String endTime) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("核酸检测预约活动记录","UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Access-Control-Expose-Headers","Content-disposition");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            List<TblOrderVo> list = tblOrderService.getOrderVoList(tblOrder,beginTime,endTime);
            EasyExcel.write(response.getOutputStream(), TblOrderVo.class).sheet("预约活动记录").doWrite(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

